<template>
  <div class="question-create-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <i class="fas fa-plus-circle"></i>
          创建新题目
        </h1>
        <p class="page-subtitle">设计和配置新的编程题目</p>
        
        <!-- 创建提示 -->
        <div class="create-tips">
          <div class="tip-item">
            <i class="fas fa-lightbulb"></i>
            <span>填写带<span class="required">*</span>的必填项即可快速创建题目</span>
          </div>
          <div class="tip-item">
            <i class="fas fa-save"></i>
            <span>创建成功后题目将保存在本地，您可以随时编辑修改</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="content-wrapper">
      <form @submit.prevent="submitQuestion" class="question-form">
        <!-- 基础信息卡片 -->
        <div class="form-card">
          <div class="card-header">
            <h3><i class="fas fa-info-circle"></i> 基础信息</h3>
          </div>
          <div class="card-content">
            <div class="form-row">
              <div class="form-group">
                <label for="questionName">题目名称 <span class="required">*</span></label>
                <input 
                  type="text" 
                  id="questionName"
                  v-model="formData.questionName"
                  placeholder="请输入题目名称，如：两数之和"
                  required
                >
              </div>
              <div class="form-group">
                <label for="courseLevelId">课程等级 <span class="required">*</span></label>
                <select id="courseLevelId" v-model="formData.courseLevelId" required>
                  <option value="">请选择课程等级</option>
                  <option value="1001">初级</option>
                  <option value="2001">中级</option>
                  <option value="3001">高级</option>
                  <option value="5001">专家级</option>
                </select>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="questionType">题目类型 <span class="required">*</span></label>
                <select id="questionType" v-model="formData.questionType" required>
                  <option value="">请选择题目类型</option>
                  <option value="1">选择题</option>
                  <option value="2">判断题</option>
                  <option value="3">填空题</option>
                  <option value="4">程序题</option>
                </select>
              </div>
              <div class="form-group">
                <label for="difficulty">难度等级 <span class="required">*</span></label>
                <select id="difficulty" v-model="formData.difficulty" required>
                  <option value="">请选择难度</option>
                  <option value="1">难度 1</option>
                  <option value="2">难度 2</option>
                  <option value="3">难度 3</option>
                  <option value="4">难度 4</option>
                  <option value="5">难度 5</option>
                  <option value="6">难度 6</option>
                </select>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="label">标签</label>
                <input 
                  type="text" 
                  id="label"
                  v-model="formData.label"
                  placeholder="如：数组,哈希表"
                >
              </div>
              <div class="form-group">
                <label for="isPublic">是否公开</label>
                <select id="isPublic" v-model="formData.isPublic">
                  <option value="1">公开</option>
                  <option value="0">私有</option>
                </select>
              </div>
            </div>

            <div class="form-row">
              <div class="form-group">
                <label for="strict">是否使用严格判题</label>
                <div class="checkbox-wrapper">
                  <input 
                    type="checkbox" 
                    id="strict"
                    v-model="formData.strict"
                    true-value="1"
                    false-value="0"
                    checked
                    disabled
                  >
                  <label for="strict" class="checkbox-label">严格判题（固定使用）</label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 题目描述卡片 -->
        <div class="form-card">
          <div class="card-header">
            <h3><i class="fas fa-edit"></i> 题目描述</h3>
          </div>
          <div class="card-content">
            <div class="form-group full-width">
              <label for="questionDescribe">题目描述（文字）<span class="required">*</span></label>
              <textarea 
                id="questionDescribe"
                v-model="formData.questionDescribe"
                placeholder="请详细描述题目要求，包括问题背景、输入输出要求等"
                rows="6"
                required
              ></textarea>
            </div>
            
            <!-- 🔥 题目描述图片上传 -->
            <div class="form-group full-width">
              <label for="questionDescribePicture">题目描述（图片）<span class="optional-tag">（选填）</span></label>
              
              <div class="test-case-file-upload-area" @click="triggerDescribeImageInput">
                <input 
                  ref="describeImageInput"
                  type="file" 
                  @change="handleDescribeImageUpload"
                  accept="image/*"
                  style="display: none"
                >
                <div v-if="uploadingDescribeImage" class="uploading-state">
                  <i class="fas fa-spinner fa-spin"></i>
                  <p>上传中...</p>
                </div>
                <div v-else-if="!formData.questionDescribePicture" class="upload-placeholder-small">
                  <i class="fas fa-image"></i>
                  <p>点击上传题目描述图片</p>
                  <small>支持 JPG、PNG、GIF</small>
                </div>
                <div v-else class="file-info-small">
                  <i class="fas fa-check-circle"></i>
                  <span>图片已上传</span>
                  <button type="button" @click.stop="removeDescribeImage" class="clear-btn-small">
                    <i class="fas fa-times"></i>
                  </button>
                </div>
              </div>
              <div v-if="formData.questionDescribePicture" class="upload-success-hint">
                <i class="fas fa-check"></i>
                <span>图片已上传到服务器</span>
              </div>
            </div>

          </div>
        </div>

        <!-- 测试用例卡片 -->
        <div class="form-card">
          <div class="card-header">
            <h3><i class="fas fa-list-alt"></i> 测试用例</h3>
          </div>
          <div class="card-content">
            <!-- 输入格式 -->
            <div class="form-group full-width">
              <label for="inputFormat">输入格式</label>
              <textarea 
                id="inputFormat"
                v-model="formData.inputFormat"
                placeholder="描述输入数据的格式，如：第一行输入两个整数 n 和 target，第二行输入 n 个整数"
                rows="2"
              ></textarea>
            </div>
            
            <!-- 输出格式 -->
            <div class="form-group full-width">
              <label for="outputFormat">输出格式</label>
              
              <!-- 输出格式类型选择 -->
              <div class="output-type-selector">
                <label class="radio-label">
                  <input 
                    type="radio" 
                    v-model="formData.outputType" 
                    value="text"
                  >
                  <span>文本描述</span>
                </label>
                <label class="radio-label">
                  <input 
                    type="radio" 
                    v-model="formData.outputType" 
                    value="local"
                  >
                  <span>上传图片</span>
                </label>
              </div>
              
              <!-- 文本格式输出 -->
              <textarea 
                v-if="formData.outputType === 'text'"
                id="outputFormat"
                v-model="formData.outputFormat"
                placeholder="如：输出一行，包含两个数字，表示满足条件的两个数的下标"
                rows="2"
              ></textarea>
              
              <!-- 图片格式输出 -->
              <div v-else-if="formData.outputType === 'local'" class="output-section">
                <div class="test-case-file-upload-area" @click="triggerOutputImageInput">
                  <input 
                    ref="outputImageInput"
                    type="file" 
                    @change="handleOutputImageUpload"
                    accept="image/*"
                    style="display: none"
                  >
                  <div v-if="uploadingOutputImage" class="uploading-state">
                    <i class="fas fa-spinner fa-spin"></i>
                    <p>上传中...</p>
                  </div>
                  <div v-else-if="!formData.outputFormat" class="upload-placeholder-small">
                    <i class="fas fa-image"></i>
                    <p>点击上传输出格式图片</p>
                    <small>支持 JPG、PNG、GIF</small>
                  </div>
                  <div v-else class="file-info-small">
                    <i class="fas fa-check-circle"></i>
                    <span>图片已上传</span>
                    <button type="button" @click.stop="removeOutputImage" class="clear-btn-small">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                </div>
                <div v-if="formData.outputFormat" class="upload-success-hint">
                  <i class="fas fa-check"></i>
                  <span>图片已上传到服务器，路径: {{ formData.outputFormat }}</span>
                </div>
              </div>
            </div>
            
            <!-- 数据范围和提示 -->
            <div class="form-group full-width">
              <label for="rangeAndPrompt">数据范围和提示 <span class="required">*</span></label>
              <textarea 
                id="rangeAndPrompt"
                v-model="formData.rangeAndPrompt"
                placeholder="如：1 <= n <= 10^4&#10;-10^9 <= nums[i] <= 10^9&#10;-10^9 <= target <= 10^9"
                rows="3"
                required
              ></textarea>
            </div>
            
            <!-- 测试用例 - 多组输入输出 -->
            <div class="form-group full-width">
              <div class="test-cases-header">
                <label>测试用例</label>
                <button type="button" @click="addTestCase" class="add-test-case-btn">
                  <i class="fas fa-plus"></i>
                  添加测试用例
                </button>
              </div>
              
              <div class="test-cases-list">
                <div v-if="testCases.length === 0" class="no-test-cases">
                  <i class="fas fa-info-circle"></i>
                  <p>暂无测试用例，点击上方按钮添加</p>
                </div>
                
                <div v-for="(testCase, index) in testCases" :key="index" class="test-case-item">
                  <div class="test-case-header">
                    <span class="test-case-number">测试用例 {{ index + 1 }}</span>
                    <button type="button" @click="removeTestCase(index)" class="remove-test-case-btn">
                      <i class="fas fa-trash"></i>
                      删除
                    </button>
                  </div>
                  
                  <div class="test-case-content">
                    <!-- 输入格式 -->
                    <div class="format-section">
                      <label>输入格式</label>
                      <textarea 
                        v-model="testCase.inputFormat"
                        placeholder="如：第一行输入两个整数 n 和 target，第二行输入 n 个整数"
                        rows="2"
                        class="test-case-format"
                      ></textarea>
                    </div>
                    
                    <!-- 输出格式 - 支持文本或图片 -->
                    <div class="format-section">
                      <label>输出格式</label>
                      
                      <!-- 输出格式类型选择 -->
                      <div class="output-type-options">
                        <div class="type-option">
                          <input 
                            type="radio" 
                            :id="'outputTypeText' + index" 
                            :name="'outputType' + index" 
                            value="text" 
                            v-model="testCase.outputType"
                          >
                          <label :for="'outputTypeText' + index">文本描述</label>
                        </div>
                        <div class="type-option">
                          <input 
                            type="radio" 
                            :id="'outputTypeImage' + index" 
                            :name="'outputType' + index" 
                            value="image" 
                            v-model="testCase.outputType"
                          >
                          <label :for="'outputTypeImage' + index">上传图片</label>
                        </div>
                      </div>

                      <!-- 文本输入 -->
                      <div v-if="testCase.outputType === 'text'" class="output-section">
                        <textarea 
                          v-model="testCase.outputFormat"
                          placeholder="如：输出一行，包含两个数字，表示满足条件的两个数的下标"
                          rows="2"
                          class="test-case-format"
                        ></textarea>
                      </div>

                      <!-- 图片上传 -->
                      <div v-if="testCase.outputType === 'image'" class="output-section">
                        <div class="test-case-file-upload-area" @click="triggerTestCaseOutputFileInput(index)">
                          <input 
                            :ref="'testCaseOutputFileInput' + index" 
                            type="file" 
                            accept="image/*" 
                            @change="handleTestCaseOutputFileSelect($event, index)" 
                            style="display: none"
                          >
                          <div v-if="testCase.uploading" class="uploading-state">
                            <i class="fas fa-spinner fa-spin"></i>
                            <p>上传中...</p>
                          </div>
                          <div v-else-if="!testCase.outputFile" class="upload-placeholder-small">
                            <i class="fas fa-image"></i>
                            <p>点击上传图片</p>
                            <small>支持 JPG、PNG、GIF</small>
                          </div>
                          <div v-else class="file-info-small">
                            <i class="fas fa-check-circle"></i>
                            <span>{{ testCase.outputFile.name }}</span>
                            <button type="button" @click.stop="clearTestCaseOutputFile(index)" class="clear-btn-small">
                              <i class="fas fa-times"></i>
                            </button>
                          </div>
                        </div>
                        <div v-if="testCase.outputFilePath" class="upload-success-hint">
                          <i class="fas fa-check"></i>
                          <span>图片已上传到服务器</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <div class="form-group full-width">
              <label>参考程序结果<span class="optional-tag">（选填）</span></label>
              
              <!-- 图片上传方式选择 -->
              <div class="image-upload-options">
                <div class="upload-option">
                  <input 
                    type="radio" 
                    id="uploadTypeUrl" 
                    name="uploadType" 
                    value="url" 
                    v-model="uploadType"
                  >
                  <label for="uploadTypeUrl">远程图片URL</label>
                </div>
                <div class="upload-option">
                  <input 
                    type="radio" 
                    id="uploadTypeFile" 
                    name="uploadType" 
                    value="file" 
                    v-model="uploadType"
                  >
                  <label for="uploadTypeFile">上传本地图片</label>
                </div>
              </div>

              <!-- 远程URL输入 -->
              <div v-if="uploadType === 'url'" class="upload-section">
                <input 
                  type="url" 
                  id="questionPicture"
                  v-model="formData.questionPicture"
                  placeholder="https://example.com/images/q1.png"
                >
                <small class="form-hint">输入图片的完整URL地址</small>
              </div>

              <!-- 本地文件上传 -->
              <div v-if="uploadType === 'file'" class="upload-section">
                <div class="file-upload-area" @click="triggerFileInput" @dragover.prevent @drop.prevent="handleFileDrop">
                  <input 
                    ref="fileInput" 
                    type="file" 
                    accept="image/*" 
                    @change="handleFileSelect" 
                    style="display: none"
                  >
                  <div v-if="!selectedFile && !uploadedImageUrl" class="upload-placeholder">
                    <i class="fas fa-cloud-upload-alt"></i>
                    <p>点击选择图片或拖拽图片到此处</p>
                    <small>支持 JPG、PNG、GIF 格式，大小不超过 5MB</small>
                  </div>
                  <div v-if="selectedFile" class="file-info">
                    <i class="fas fa-image"></i>
                    <span>{{ selectedFile.name }}</span>
                    <button type="button" @click.stop="clearFile" class="clear-btn">
                      <i class="fas fa-times"></i>
                    </button>
                  </div>
                </div>
                
                <small class="form-hint">选择图片文件后，在创建题目时会一并上传</small>
              </div>

              <!-- 图片预览（URL方式） -->
              <div v-if="uploadType === 'url' && formData.questionPicture" class="image-preview">
                <img :src="formData.questionPicture" alt="图片预览" class="preview-image-small" @error="onImageError">
              </div>
            </div>

            <div class="form-group full-width">
              <label for="testCode">答案 <span class="required">*</span></label>
              <textarea 
                id="testCode"
                v-model="formData.testCode"
                placeholder="请输入题目的标准答案或解题思路"
                rows="4"
                required
              ></textarea>
              <small class="form-hint">请提供题目的标准答案，这将帮助系统进行自动判题</small>
            </div>

            <!-- 测试数据 -->
            <div class="form-group full-width">
              <div class="test-cases-header">
                <label>测试数据</label>
                <button type="button" @click="addTestData" class="add-test-case-btn">
                  <i class="fas fa-plus"></i>
                  添加测试数据
                </button>
              </div>
              
              <div class="test-cases-list">
                <div v-if="testDataItems.length === 0" class="no-test-cases">
                  <i class="fas fa-info-circle"></i>
                  <p>暂无测试数据，点击上方按钮添加</p>
                </div>
                
                <div v-for="(testData, index) in testDataItems" :key="index" class="test-case-item">
                  <div class="test-case-header">
                    <span class="test-case-number">测试数据 {{ index + 1 }}</span>
                    <button type="button" @click="removeTestData(index)" class="remove-test-case-btn">
                      <i class="fas fa-trash"></i>
                      删除
                    </button>
                  </div>
                  
                  <div class="test-case-content">
                    <div class="format-section">
                      <textarea 
                        v-model="testData.content"
                        placeholder="请输入测试数据，如：3 9&#10;2 7 11 15"
                        rows="4"
                        class="test-case-format"
                      ></textarea>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 限制条件卡片 -->
        <div class="form-card">
          <div class="card-header">
            <h3><i class="fas fa-cog"></i> 限制条件</h3>
          </div>
          <div class="card-content">
            <div class="form-row">
              <div class="form-group">
                <label for="timeLimit">时间限制 (毫秒) <span class="required">*</span></label>
                <input 
                  type="number" 
                  id="timeLimit"
                  v-model.number="formData.timeLimit"
                  placeholder="1000"
                  min="100"
                  max="10000"
                  required
                >
                <small class="form-hint">建议范围：100-10000毫秒</small>
              </div>
              <div class="form-group">
                <label for="spaceLimitation">空间限制 (字节) <span class="required">*</span></label>
                <input 
                  type="number" 
                  id="spaceLimitation"
                  v-model.number="formData.spaceLimitation"
                  placeholder="268435456"
                  min="1048576"
                  required
                >
                <small class="form-hint">建议最小值：1MB (1048576字节)</small>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <button type="button" @click="goBack" class="btn btn-secondary">
            <i class="fas fa-arrow-left"></i>
            取消
          </button>
          <button type="button" @click="saveAsDraft" class="btn btn-outline">
            <i class="fas fa-save"></i>
            保存草稿
          </button>
          <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
            <i class="fas fa-check"></i>
            {{ isSubmitting ? '创建中...' : '创建题目' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script>
import { createTestQuestion } from '@/api/testQuestion'
import { uploadFile } from '@/api/file'
import logger from '../utils/logger.js'

export default {
  name: 'QuestionCreate',
  data() {
    return {
      isSubmitting: false,
      // 图片上传相关
      uploadType: '', // 不默认选择，让用户自己选择 'url' 或 'file'
      selectedFile: null,
      // 输出格式类型
      outputFormatType: '', // 不默认选择，让用户自己选择 'text' 或 'image'
      selectedOutputFile: null, // 输出格式图片文件
      uploadingOutputImage: false, // 全局输出格式图片上传状态
      uploadingDescribeImage: false, // 题目描述图片上传状态
      // 测试用例数组
      testCases: [],
      // 测试数据数组
      testDataItems: [],
      formData: {
        createUserId: null, // 将在mounted中设置为当前用户ID
        courseLevelId: '',
        questionName: '',
        questionType: '',
        isPublic: 1,
        strict: 1, // 🔥 是否使用严格判题，固定为严格模式，integer类型
        timeLimit: 1000,
        spaceLimitation: 268435456,
        questionDescribe: '',
        questionDescribePicture: '', // 🔥 题目描述图片路径（string类型）
        questionPicture: '',
        inputFormat: '',
        outputFormat: '', // 输出格式：可以是文本描述或图片路径（string类型）
        outputType: '', // 输出格式类型：text=文本描述，local=上传图片（仅用于UI控制，不传给后端）
        rangeAndPrompt: '',
        testCases: '', // 测试用例 (string类型)
        testCode: '',
        testData: '', // 测试数据 (string类型)
        difficulty: '',
        label: '',
        submissionQuantity: 0,
        byQuantity: 0
      }
    }
  },
  methods: {
    async submitQuestion() {
      logger.log('🎬 [QuestionCreate] ========== 开始提交题目 ==========');
      
      if (!this.validateForm()) {
        logger.log('❌ [QuestionCreate] 表单验证失败，停止提交');
        return;
      }
      
      // 验证测试用例
      for (let i = 0; i < this.testCases.length; i++) {
        const tc = this.testCases[i];
        if (tc.outputType === 'image' && !tc.outputFilePath) {
          const errorMsg = `测试用例${i + 1}选择了图片输出但图片未上传成功，请重新上传`;
          logger.error('❌ [QuestionCreate]', errorMsg);
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg);
          } else {
            alert('❌ ' + errorMsg);
          }
          return;
        }
      }

      logger.log('⏳ [QuestionCreate] 设置提交状态...');
      this.isSubmitting = true;
      
      try {
        logger.log('🚀 [QuestionCreate] 开始创建题目...');
        logger.log('📝 [QuestionCreate] 题目数据:', this.formData);
        logger.log('🖼️ [QuestionCreate] 上传类型:', this.uploadType);
        logger.log('🌐 [QuestionCreate] 将要调用的API地址: /goc/testQuestion/add');
        logger.log('📊 [QuestionCreate] 请求方法: POST');

        // 确保用户ID存在
        if (!this.formData.createUserId) {
          logger.warn('⚠️ [QuestionCreate] createUserId为空，重新获取...');
          this.formData.createUserId = this.getCurrentUserId();
          logger.log('👤 [QuestionCreate] 重新设置的用户ID:', this.formData.createUserId);
        }

        // 确保数据类型正确
        const submitData = {
          ...this.formData,
          createUserId: this.formData.createUserId, // 保持原始字符串，在API层处理为long类型
          courseLevelId: Number(this.formData.courseLevelId),
          questionType: Number(this.formData.questionType),
          isPublic: Number(this.formData.isPublic),
          strict: 1, // 🔥 固定为严格判题模式，始终传 1（integer类型）
          timeLimit: Number(this.formData.timeLimit),
          spaceLimitation: String(this.formData.spaceLimitation), // 根据接口文档，应为字符串类型
          testCases: JSON.stringify(this.testCases.map(tc => ({
            input: tc.inputFormat || '',  // 输入格式放进input
            output: tc.outputType === 'image' ? (tc.outputFilePath || '') : (tc.outputFormat || '')  // 输出格式（文本或图片路径）放进output
          }))), // 将测试用例数组转换为指定格式的JSON字符串
          testData: JSON.stringify(this.testDataItems.map(td => ({
            content: td.content || ''  // 测试数据内容
          }))), // 将测试数据数组转换为指定格式的JSON字符串
          difficulty: Number(this.formData.difficulty),
          submissionQuantity: Number(this.formData.submissionQuantity),
          byQuantity: Number(this.formData.byQuantity)
        };

        logger.log('📋 [QuestionCreate] 最终提交的数据:');
        logger.log('👤 [QuestionCreate] createUserId:', submitData.createUserId, '(类型:', typeof submitData.createUserId, ')');
        logger.log('👤 [QuestionCreate] createUserId长度:', String(submitData.createUserId).length, '位');
        logger.log('🧪 [QuestionCreate] ========== 测试用例格式转换 ==========');
        logger.log('🧪 [QuestionCreate] 原始测试用例数据:', this.testCases);
        logger.log('🧪 [QuestionCreate] 转换后的测试用例:', submitData.testCases);
        logger.log('🧪 [QuestionCreate] testCases类型:', typeof submitData.testCases);
        logger.log('🧪 [QuestionCreate] testCases长度:', submitData.testCases ? submitData.testCases.length : 0);
        // 解析并显示转换后的内容
        try {
          const parsedTestCases = JSON.parse(submitData.testCases);
          logger.log('🧪 [QuestionCreate] 解析后的测试用例数组:', parsedTestCases);
          parsedTestCases.forEach((tc, idx) => {
            logger.log(`  测试用例${idx + 1}:`);
            logger.log(`    - input: ${tc.input}`);
            logger.log(`    - output: ${tc.output}`);
          });
        } catch (e) {
          logger.error('❌ [QuestionCreate] 解析测试用例失败:', e);
        }
        logger.log('🖼️ [QuestionCreate] pictureType:', submitData.pictureType);
        logger.log('📊 [QuestionCreate] 完整提交数据:', submitData);
        
        // 🔥 调试输入输出格式数据
        logger.log('🔍 [QuestionCreate] ========== 输入输出格式数据检查 ==========');
        logger.log('🔍 [QuestionCreate] formData.inputFormat:', this.formData.inputFormat);
        logger.log('🔍 [QuestionCreate] formData.outputType (UI选择):', this.formData.outputType);
        logger.log('🔍 [QuestionCreate] formData.outputFormat (文本或图片路径):', this.formData.outputFormat);
        logger.log('🔍 [QuestionCreate] submitData.inputFormat:', submitData.inputFormat);
        logger.log('🔍 [QuestionCreate] submitData.outputFormat:', submitData.outputFormat);

        // 🔥 简化：后端不需要 outputType，outputFormat 可以是文本或图片路径
        // outputFormat 的值：
        //   - 文本描述时：用户填写的文本内容
        //   - 上传图片时：后端返回的图片路径
        // 后端会自动判断 outputFormat 是文本还是图片路径
        
        // 删除 outputType 和 outputFile 字段（后端不需要）
        delete submitData.outputType;
        delete submitData.outputFile;
        
        logger.log('✅ [QuestionCreate] 输出格式处理完成:');
        logger.log('  - inputFormat:', submitData.inputFormat);
        logger.log('  - outputFormat:', submitData.outputFormat, '(可能是文本或图片路径)');

        // 处理参考程序结果图片上传
        if (this.uploadType === 'file' && this.selectedFile) {
          logger.log('📤 [QuestionCreate] 包含本地图片文件');
          // 将文件对象直接添加到提交数据，FormData会正确处理
          submitData.pictureFile = this.selectedFile;
          submitData.pictureType = 'local'; // 本地图片类型
          logger.log('📸 [QuestionCreate] 图片文件:', this.selectedFile.name, '类型: local');
        } else if (this.uploadType === 'url' && this.formData.questionPicture) {
          logger.log('📤 [QuestionCreate] 使用远程图片URL');
          submitData.pictureType = 'remote'; // 远程图片类型
          logger.log('🌐 [QuestionCreate] 远程图片URL:', this.formData.questionPicture, '类型: remote');
        } else {
          logger.log('📤 [QuestionCreate] 未选择图片上传方式，设置为空');
          // 不选择图片时，删除相关字段或设置为null
          delete submitData.pictureType;
          delete submitData.questionPicture;
          delete submitData.pictureFile;
          logger.log('✅ [QuestionCreate] 已清除图片相关字段');
        }
          
        // 调用API创建题目（现在统一使用FormData格式）
        const response = await createTestQuestion(submitData);
        logger.log('🎉 [QuestionCreate] API响应:', response);
        logger.log('🎉 [QuestionCreate] 响应状态:', response?.status);
        logger.log('🎉 [QuestionCreate] 响应数据:', response?.data);
        
        // 🔥 重要：必须检查后端返回的业务状态码 code
        const responseData = response?.data;
        logger.log('🔍 [QuestionCreate] 检查业务状态码...');
        logger.log('🔍 [QuestionCreate] responseData.code:', responseData?.code);
        logger.log('🔍 [QuestionCreate] responseData.message:', responseData?.message);
        
        // 只有当 code === 0 时才是成功
        if (responseData && responseData.code === 0) {
          logger.log('✅ [QuestionCreate] 题目创建成功（code = 0）');
          
          // 保存到本地存储
          try {
            logger.log('💾 [QuestionCreate] 保存题目到本地存储...');
            const { default: localQuestionStorage } = await import('@/utils/localStorage');
            const savedQuestion = localQuestionStorage.saveQuestion(submitData);
            logger.log('✅ [QuestionCreate] 题目已保存到本地存储，ID:', savedQuestion.id);
          } catch (storageError) {
            logger.error('⚠️ [QuestionCreate] 保存到本地存储失败:', storageError);
            // 本地存储失败不影响主流程
          }
          
          // 显示成功消息
          logger.log('✅ [QuestionCreate] 题目创建成功');
          
          // 短暂延迟后跳转，确保用户看到成功消息
          logger.log('🚀 [QuestionCreate] 准备跳转到题目列表页面...');
          
          // 立即跳转的备选方案
          if (!this.$message) {
            // 如果没有消息组件，立即跳转
            logger.log('🚀 [QuestionCreate] 立即跳转到我的试题页面（无消息组件）');
            this.$router.push('/my-questions');
          } else {
            // 有消息组件时，延迟跳转让用户看到成功提示
            setTimeout(() => {
              logger.log('🚀 [QuestionCreate] 延迟跳转到我的试题页面');
              this.$router.push('/my-questions');
            }, 1500); // 1.5秒后跳转
          }
        } else {
          // 🔥 code !== 0，表示业务逻辑失败
          logger.error('❌ [QuestionCreate] 题目创建失败，业务状态码异常');
          logger.error('❌ [QuestionCreate] code:', responseData?.code);
          logger.error('❌ [QuestionCreate] message:', responseData?.message);
          
          const errorMsg = responseData?.message || '创建题目失败，请检查输入信息';
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg);
          } else {
            alert('❌ ' + errorMsg);
          }
          
          // 不要跳转，让用户修改后重试
          return;
        }
        
      } catch (error) {
        logger.error('❌ [QuestionCreate] 创建题目失败:', error);
        logger.error('❌ [QuestionCreate] 错误详情:', error.message);
        logger.error('❌ [QuestionCreate] 错误堆栈:', error.stack);
        
        // 🔥 根据后端返回的实际错误信息显示
        let errorMsg = '创建题目失败，请重试';
        
        // 尝试从各种可能的位置获取后端错误信息
        if (error.response?.data?.message) {
          errorMsg = error.response.data.message;
        } else if (error.data?.message) {
          errorMsg = error.data.message;
        } else if (error.message) {
          errorMsg = error.message;
        }
        
        logger.error('❌ [QuestionCreate] 显示错误消息:', errorMsg);
        
        // 安全地显示错误消息
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg);
        } else {
          alert('❌ ' + errorMsg);
        }
      } finally {
        logger.log('🔄 [QuestionCreate] 重置提交状态...');
        this.isSubmitting = false;
        logger.log('🎬 [QuestionCreate] ========== 提交流程结束 ==========');
      }
    },

    validateForm() {
      // 🔥 questionDescribe 现在是必填项
      const required = ['questionName', 'courseLevelId', 'questionType', 'difficulty', 'questionDescribe', 'rangeAndPrompt', 'testCode'];
      
      logger.log('🔍 [QuestionCreate] 开始表单验证...');
      logger.log('🔍 [QuestionCreate] 当前表单数据:', this.formData);
      
      for (let field of required) {
        if (!this.formData[field]) {
          logger.error(`❌ [QuestionCreate] 缺少必填字段: ${field}`);
          const errorMsg = `请填写${this.getFieldLabel(field)}`;
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg);
          } else {
            alert(errorMsg);
          }
          return false;
        }
      }
      
      logger.log('✅ [QuestionCreate] 必填字段验证通过');

      // 🔥 验证：参考程序结果（选填项） - 如果选择了上传方式，则验证对应字段
      if (this.uploadType) {
        // 如果选择了远程URL但未填写URL
        if (this.uploadType === 'url' && !this.formData.questionPicture) {
          const errorMsg = '请输入参考程序结果图片的远程URL地址';
          logger.error('❌ [QuestionCreate] 选择了远程URL但未填写');
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg);
          } else {
            alert('❌ ' + errorMsg);
          }
          return false;
        }
        
        // 如果选择了本地图片但未上传文件
        if (this.uploadType === 'file' && !this.selectedFile) {
          const errorMsg = '请上传参考程序结果的本地图片文件';
          logger.error('❌ [QuestionCreate] 选择了本地图片但未上传');
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg);
          } else {
            alert('❌ ' + errorMsg);
          }
          return false;
        }
        
        logger.log('✅ [QuestionCreate] 参考程序结果验证通过');
      } else {
        logger.log('ℹ️ [QuestionCreate] 未选择参考程序结果，跳过验证（选填项）');
      }

      if (this.formData.timeLimit < 100 || this.formData.timeLimit > 10000) {
        const errorMsg = '时间限制应在100-10000毫秒之间';
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg);
        } else {
          alert(errorMsg);
        }
        return false;
      }

      if (this.formData.spaceLimitation < 1048576) {
        const errorMsg = '空间限制不能小于1MB';
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg);
        } else {
          alert(errorMsg);
        }
        return false;
      }

      logger.log('✅ [QuestionCreate] 所有验证通过');
      return true;
    },

    getFieldLabel(field) {
      const labels = {
        questionName: '题目名称',
        courseLevelId: '课程等级',
        questionType: '题目类型',
        difficulty: '难度等级',
        questionDescribe: '题目描述',
        inputFormat: '输入格式',
        outputFormat: '输出格式',
        rangeAndPrompt: '数据范围和提示',
        testCases: '测试用例',
        testCode: '答案'
      };
      return labels[field] || field;
    },

    saveAsDraft() {
      logger.log('💾 [QuestionCreate] 保存草稿:', this.formData);
      localStorage.setItem('questionDraft', JSON.stringify(this.formData));
      logger.log('✅ [QuestionCreate] 草稿已保存');
    },

    // 添加测试用例
    addTestCase() {
      this.testCases.push({
        inputFormat: '',
        outputType: 'text',  // 默认为文本描述
        outputFormat: '',
        outputFile: null,  // 输出格式图片文件
        outputFilePath: null,  // 输出格式图片路径（后端返回）
        uploading: false  // 上传中状态
      })
      logger.log('➕ [QuestionCreate] 添加测试用例，当前数量:', this.testCases.length)
    },
    
    // 删除测试用例
    removeTestCase(index) {
      if (confirm('确定要删除这个测试用例吗？')) {
        this.testCases.splice(index, 1)
        logger.log('🗑️ [QuestionCreate] 删除测试用例，当前数量:', this.testCases.length)
      }
    },
    
    // 添加测试数据
    addTestData() {
      this.testDataItems.push({
        content: ''
      })
      logger.log('➕ [QuestionCreate] 添加测试数据，当前数量:', this.testDataItems.length)
    },
    
    // 删除测试数据
    removeTestData(index) {
      if (confirm('确定要删除这条测试数据吗？')) {
        this.testDataItems.splice(index, 1)
        logger.log('🗑️ [QuestionCreate] 删除测试数据，当前数量:', this.testDataItems.length)
      }
    },
    
    // 触发测试用例输出格式文件选择
    triggerTestCaseOutputFileInput(index) {
      const inputElement = this.$refs['testCaseOutputFileInput' + index]
      if (inputElement && inputElement[0]) {
        inputElement[0].click()
      }
    },
    
    // 处理测试用例输出格式文件选择
    async handleTestCaseOutputFileSelect(event, index) {
      const file = event.target.files[0]
      if (file) {
        // 验证文件大小（5MB限制）
        if (file.size > 5 * 1024 * 1024) {
          alert('图片文件不能超过5MB')
          return
        }
        
        // 设置上传中状态
        if (this.testCases && Array.isArray(this.testCases) && this.testCases[index]) {
          this.testCases[index].uploading = true
        }
        
        // 自动上传文件
        try {
          logger.log(`📤 [QuestionCreate] 开始上传测试用例${index + 1}输出格式图片...`)
          
          const response = await uploadFile(file)
          
          if (response && response.code === 0 && response.data) {
            // 保存文件对象和后端返回的图片路径
            if (this.testCases && Array.isArray(this.testCases) && this.testCases[index]) {
              this.testCases[index].outputFile = file
              this.testCases[index].outputFilePath = response.data  // 保存图片路径
            }
            
            logger.log(`✅ [QuestionCreate] 测试用例${index + 1}图片上传成功，路径:`, response.data)
          } else {
            throw new Error(response?.message || '上传失败')
          }
        } catch (error) {
          logger.error(`❌ [QuestionCreate] 测试用例${index + 1}图片上传失败:`, error)
          
          const errorMsg = error.response?.data?.message || error.message || '图片上传失败'
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg)
          } else {
            alert('❌ ' + errorMsg)
          }
        } finally {
          // 清除上传中状态
          if (this.testCases && Array.isArray(this.testCases) && this.testCases[index]) {
            this.testCases[index].uploading = false
          }
        }
      }
    },
    
    // 清除测试用例输出格式文件
    clearTestCaseOutputFile(index) {
      // 清除文件对象和路径，允许重新选择
      if (this.testCases && Array.isArray(this.testCases) && this.testCases[index]) {
        this.testCases[index].outputFile = null
        this.testCases[index].outputFilePath = null
        this.testCases[index].uploading = false
      }
      logger.log(`🗑️ [QuestionCreate] 清除测试用例${index + 1}输出格式图片`)
    },
    
    // 🔥 触发全局输出格式图片选择
    triggerOutputImageInput() {
      const inputElement = this.$refs.outputImageInput
      if (inputElement) {
        inputElement.click()
      }
    },
    
    // 🔥 处理全局输出格式图片上传
    async handleOutputImageUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 验证文件大小（5MB限制）
      if (file.size > 5 * 1024 * 1024) {
        alert('图片文件不能超过5MB')
        return
      }
      
      // 设置上传中状态
      this.uploadingOutputImage = true
      
      try {
        logger.log('📤 [QuestionCreate] 开始上传输出格式图片...')
        
        const response = await uploadFile(file)
        
        if (response && response.code === 0 && response.data) {
          // 🔥 重要：将后端返回的图片路径保存到 outputFormat 字段（不是 outputFile）
          this.formData.outputFormat = response.data
          logger.log('✅ [QuestionCreate] 输出格式图片上传成功，路径已保存到 outputFormat:', response.data)
          
          if (this.$message && this.$message.success) {
            this.$message.success({
              message: '图片上传成功',
              duration: 1000
            })
          }
        } else {
          throw new Error(response?.message || '上传失败')
        }
      } catch (error) {
        logger.error('❌ [QuestionCreate] 输出格式图片上传失败:', error)
        
        const errorMsg = error.response?.data?.message || error.message || '图片上传失败'
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg)
        } else {
          alert('❌ ' + errorMsg)
        }
        
        // 清除文件选择
        event.target.value = ''
      } finally {
        // 清除上传中状态
        this.uploadingOutputImage = false
      }
    },
    
    // 🔥 移除全局输出格式图片
    removeOutputImage() {
      this.formData.outputFormat = ''
      logger.log('🗑️ [QuestionCreate] 移除输出格式图片，清空 outputFormat')
    },
    
    // 🔥 触发题目描述图片选择
    triggerDescribeImageInput() {
      const inputElement = this.$refs.describeImageInput
      if (inputElement) {
        inputElement.click()
      }
    },
    
    // 🔥 处理题目描述图片上传
    async handleDescribeImageUpload(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 验证文件大小（5MB限制）
      if (file.size > 5 * 1024 * 1024) {
        alert('图片文件不能超过5MB')
        return
      }
      
      // 设置上传中状态
      this.uploadingDescribeImage = true
      
      try {
        logger.log('📤 [QuestionCreate] 开始上传题目描述图片...')
        
        const response = await uploadFile(file)
        
        if (response && response.code === 0 && response.data) {
          // 保存后端返回的图片路径到 questionDescribePicture 字段
          this.formData.questionDescribePicture = response.data
          logger.log('✅ [QuestionCreate] 题目描述图片上传成功，路径:', response.data)
          
          if (this.$message && this.$message.success) {
            this.$message.success({
              message: '图片上传成功',
              duration: 1000
            })
          }
        } else {
          throw new Error(response?.message || '上传失败')
        }
      } catch (error) {
        logger.error('❌ [QuestionCreate] 题目描述图片上传失败:', error)
        
        const errorMsg = error.response?.data?.message || error.message || '图片上传失败'
        if (this.$message && this.$message.error) {
          this.$message.error(errorMsg)
        } else {
          alert('❌ ' + errorMsg)
        }
        
        // 清除文件选择
        event.target.value = ''
      } finally {
        // 清除上传中状态
        this.uploadingDescribeImage = false
      }
    },
    
    // 🔥 移除题目描述图片
    removeDescribeImage() {
      this.formData.questionDescribePicture = ''
      logger.log('🗑️ [QuestionCreate] 移除题目描述图片')
    },

    goBack() {
      this.$router.go(-1);
    },

    loadDraft() {
      const draft = localStorage.getItem('questionDraft');
      if (draft) {
        try {
          const draftData = JSON.parse(draft);
          this.formData = { ...this.formData, ...draftData };
          if (this.$message && this.$message.info) {
            this.$message.info('已加载上次保存的草稿');
          } else {
            logger.log('✅ [QuestionCreate] 已加载上次保存的草稿');
          }
        } catch (error) {
          logger.error('加载草稿失败:', error);
        }
      }
    },

    // 手动跳转方法
    manualRedirect() {
      logger.log('🔧 [QuestionCreate] 手动触发跳转到我的试题页面...');
      try {
        this.$router.push('/my-questions');
        logger.log('✅ [QuestionCreate] 手动跳转命令已发送');
      } catch (error) {
        logger.error('❌ [QuestionCreate] 手动跳转失败:', error);
        // 备选方案：直接修改URL
        window.location.href = '/my-questions';
      }
    },

    // 获取当前用户ID（修复精度丢失问题）
    getCurrentUserId() {
      try {
        // 首先尝试从JWT令牌中解析用户ID
        const token = localStorage.getItem('token');
        if (token) {
          try {
            const tokenParts = token.split('.');
            if (tokenParts.length === 3) {
              // 关键修复：直接解析base64字符串，避免JSON.parse的数字精度丢失
              const payloadBase64 = tokenParts[1];
              const payloadStr = atob(payloadBase64);
              logger.log('🔍 [QuestionCreate] JWT payload字符串:', payloadStr);
              
              // 使用正则表达式提取ID，保持字符串格式
              const idMatch = payloadStr.match(/"id":(\d+)/);
              if (idMatch && idMatch[1]) {
                const userId = idMatch[1]; // 保持字符串格式
                logger.log('👤 [QuestionCreate] 从JWT令牌获取用户ID (字符串格式):', userId);
                logger.log('👤 [QuestionCreate] 用户ID长度:', userId.length, '位');
                return userId;
              }
              
              // 备用方案：如果正则匹配失败，使用JSON.parse但立即转为字符串
              const payload = JSON.parse(payloadStr);
              const userIdNum = payload.claims?.id;
              if (userIdNum) {
                const userId = String(userIdNum);
                logger.warn('⚠️ [QuestionCreate] 使用备用方案获取用户ID，可能有精度丢失:', userId);
                return userId;
              }
            }
          } catch (tokenError) {
            logger.warn('⚠️ [QuestionCreate] JWT令牌解析失败:', tokenError);
          }
        }
        
        // 备选方案：从localStorage获取用户信息
        const userInfoStr = localStorage.getItem('userInfo');
        if (userInfoStr) {
          const userInfo = JSON.parse(userInfoStr);
          logger.log('👤 [QuestionCreate] 从localStorage获取用户信息:', userInfo);
          const userId = String(userInfo.id || '1953810929896525824'); // 确保字符串格式
          logger.log('👤 [QuestionCreate] 从localStorage获取用户ID (字符串格式):', userId);
          return userId;
        }
      } catch (error) {
        logger.error('❌ [QuestionCreate] 解析用户信息失败:', error);
      }
      logger.warn('⚠️ [QuestionCreate] 无法获取用户ID，使用正确的默认值');
      return '1953810929896525824'; // 使用正确的用户ID
    },

    // 图片上传相关方法
    triggerFileInput() {
      this.$refs.fileInput.click()
    },

    async handleFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        // 验证文件
        if (file.size > 5 * 1024 * 1024) {
          alert('图片文件不能超过5MB')
          return
        }
        
        // 自动上传文件
        try {
          logger.log('📤 [QuestionCreate] 开始上传参考程序结果图片...')
          
          const response = await uploadFile(file)
          
          if (response && response.code === 0 && response.data) {
            // 保存后端返回的图片路径
            this.formData.questionPicture = response.data
            this.selectedFile = file
            
            logger.log('✅ [QuestionCreate] 参考程序结果图片上传成功，路径:', response.data)
          } else {
            throw new Error(response?.message || '上传失败')
          }
        } catch (error) {
          logger.error('❌ [QuestionCreate] 图片上传失败:', error)
          
          const errorMsg = error.response?.data?.message || error.message || '图片上传失败'
          if (this.$message && this.$message.error) {
            this.$message.error(errorMsg)
          } else {
            alert('❌ ' + errorMsg)
          }
        }
      }
    },

    handleFileDrop(event) {
      const files = event.dataTransfer.files
      if (files.length > 0) {
        this.validateAndSetFile(files[0])
      }
    },

    validateAndSetFile(file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件（JPG、PNG、GIF等格式）')
        return
      }

      // 检查文件大小（5MB限制）
      const maxSize = 5 * 1024 * 1024 // 5MB
      if (file.size > maxSize) {
        alert('图片大小不能超过5MB')
        return
      }

      this.selectedFile = file
      logger.log('✅ [QuestionCreate] 文件选择成功:', file.name, '大小:', (file.size / 1024 / 1024).toFixed(2) + 'MB')
    },

    clearFile() {
      this.selectedFile = null
      this.$refs.fileInput.value = ''
    },

    // 输出格式图片上传相关方法
    triggerOutputFileInput() {
      this.$refs.outputFileInput.click()
    },

    handleOutputFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        this.validateAndSetOutputFile(file)
      }
    },

    handleOutputFileDrop(event) {
      const files = event.dataTransfer.files
      if (files.length > 0) {
        this.validateAndSetOutputFile(files[0])
      }
    },

    validateAndSetOutputFile(file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件（JPG、PNG、GIF等格式）')
        return
      }

      // 检查文件大小（5MB限制）
      const maxSize = 5 * 1024 * 1024 // 5MB
      if (file.size > maxSize) {
        alert('图片大小不能超过5MB')
        return
      }

      this.selectedOutputFile = file
      logger.log('✅ [QuestionCreate] 输出格式图片选择成功:', file.name, '大小:', (file.size / 1024 / 1024).toFixed(2) + 'MB')
    },

    clearOutputFile() {
      this.selectedOutputFile = null
      this.$refs.outputFileInput.value = ''
    },



    onImageError(event) {
      logger.error('❌ [QuestionCreate] 图片预览加载失败:', event.target.src)
      event.target.style.display = 'none'
    },

    // 将文件转换为base64字符串
    fileToBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => {
          // 移除data:image/xxx;base64,前缀，只保留base64字符串
          const base64 = reader.result.split(',')[1]
          resolve(base64)
        }
        reader.onerror = () => {
          reject(new Error('文件读取失败'))
        }
        reader.readAsDataURL(file)
      })
    }
  },

  mounted() {
    logger.log('📋 [QuestionCreate] 题目创建页面已加载');
    logger.log('🔍 [QuestionCreate] Vue实例检查:');
    logger.log('  - this.$message:', !!this.$message);
    logger.log('  - this.$router:', !!this.$router);
    logger.log('  - 当前路由:', this.$route.path);
    logger.log('  - Vue组件已挂载');
    
    // 设置当前用户ID
    this.formData.createUserId = this.getCurrentUserId();
    logger.log('👤 [QuestionCreate] 设置用户ID为:', this.formData.createUserId);
    
    this.loadDraft();
  }
}
</script>

<style scoped>
.question-create-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.header-content {
  background: rgba(255, 255, 255, 0.95);
  padding: 30px;
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  display: inline-block;
}

.page-title {
  font-size: 2.5em;
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-weight: 700;
}

.page-title i {
  color: #667eea;
  margin-right: 15px;
}

.page-subtitle {
  font-size: 1.1em;
  color: #7f8c8d;
  margin: 0;
}

.create-tips {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #fff3cd, #ffeaa7);
  border: 1px solid #ffeaa7;
  border-radius: 8px;
  color: #856404;
}

.create-tips .tip-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.create-tips .tip-item i {
  color: #f39c12;
  font-size: 16px;
  min-width: 16px;
}

.create-tips .required {
  color: #e74c3c;
  font-weight: 600;
}

.content-wrapper {
  max-width: 1000px;
  margin: 0 auto;
}

.question-form {
  display: flex;
  flex-direction: column;
  gap: 25px;
}

.form-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.form-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

.card-header {
  background: linear-gradient(135deg, #667eea, #764ba2);
  padding: 20px 30px;
  color: white;
}

.card-header h3 {
  margin: 0;
  font-size: 1.3em;
  font-weight: 600;
}

.card-header i {
  margin-right: 10px;
}

.card-content {
  padding: 30px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row:last-child {
  margin-bottom: 0;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group.full-width {
  grid-column: 1 / -1;
}

.form-group label {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 0.95em;
}

.optional-tag {
  font-size: 0.85em;
  color: #999;
  font-weight: 400;
  margin-left: 4px;
}

.required {
  color: #e74c3c;
  font-weight: bold;
}

.form-group input,
.form-group select,
.form-group textarea {
  padding: 12px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 0.95em;
  transition: all 0.3s ease;
  background: white;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  transform: translateY(-2px);
}

.form-group textarea {
  resize: vertical;
  min-height: 60px;
  font-family: inherit;
}

.form-hint {
  margin-top: 5px;
  font-size: 0.85em;
  color: #7f8c8d;
  font-style: italic;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 30px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.btn {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  font-size: 1em;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(102, 126, 234, 0.3);
}

.btn-secondary {
  background: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background: #7f8c8d;
  transform: translateY(-2px);
}

.btn-outline {
  background: transparent;
  color: #667eea;
  border: 2px solid #667eea;
}

.btn-outline:hover {
  background: #667eea;
  color: white;
  transform: translateY(-2px);
}

/* 输出格式类型选择器 */
.output-type-selector {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #555;
}

.radio-label input[type="radio"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.radio-label span {
  user-select: none;
}

/* 文件上传区域 - 统一样式 */
.test-case-file-upload-area {
  border: 2px dashed #d0d0d0;
  border-radius: 12px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
  min-height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.test-case-file-upload-area:hover {
  border-color: #667eea;
  background: #f5f7ff;
}

/* 上传中状态 */
.uploading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #667eea;
}

.uploading-state i {
  font-size: 32px;
}

.uploading-state p {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

/* 上传占位符 */
.upload-placeholder-small {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: #999;
}

.upload-placeholder-small i {
  font-size: 40px;
  color: #d0d0d0;
}

.upload-placeholder-small p {
  margin: 0;
  font-size: 15px;
  font-weight: 500;
  color: #666;
}

.upload-placeholder-small small {
  font-size: 12px;
  color: #999;
}

/* 文件信息显示 */
.file-info-small {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #4CAF50;
  font-size: 14px;
  font-weight: 500;
}

.file-info-small i {
  font-size: 20px;
}

.clear-btn-small {
  background: #f44336;
  color: white;
  border: none;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  margin-left: auto;
}

.clear-btn-small:hover {
  background: #d32f2f;
  transform: scale(1.1);
}

.clear-btn-small i {
  font-size: 12px;
}

/* 上传成功提示 */
.upload-success-hint {
  margin-top: 10px;
  padding: 8px 12px;
  background: #e8f5e9;
  color: #4CAF50;
  border-radius: 6px;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.upload-success-hint i {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .question-create-container {
    padding: 10px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .page-title {
    font-size: 2em;
  }
  
  .card-content {
    padding: 20px;
  }
  
  .form-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .btn {
    justify-content: center;
  }
}

/* 动画效果 */
.form-card {
  animation: fadeInUp 0.6s ease forwards;
}

.form-card:nth-child(1) { animation-delay: 0.1s; }
.form-card:nth-child(2) { animation-delay: 0.2s; }
.form-card:nth-child(3) { animation-delay: 0.3s; }
.form-card:nth-child(4) { animation-delay: 0.4s; }

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 表单验证样式 */
.form-group input:invalid:not(:focus),
.form-group select:invalid:not(:focus),
.form-group textarea:invalid:not(:focus) {
  border-color: #e74c3c;
}

.form-group input:valid,
.form-group select:valid,
.form-group textarea:valid {
  border-color: #27ae60;
}

/* 图片上传样式 */
.image-upload-options {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.upload-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.upload-option input[type="radio"] {
  margin: 0;
  width: auto;
}

.upload-option label {
  margin: 0;
  cursor: pointer;
  font-weight: normal;
}

.upload-section {
  margin-top: 15px;
}

.upload-section input[type="url"] {
  width: 100%;
  min-width: 400px;
  padding: 12px 15px;
  font-size: 14px;
  border: 2px solid #ddd;
  border-radius: 8px;
  transition: border-color 0.3s ease;
}

.upload-section input[type="url"]:focus {
  border-color: #3498db;
  outline: none;
  box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1);
}

.file-upload-area {
  border: 2px dashed #ddd;
  border-radius: 10px;
  padding: 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
  position: relative;
}

.file-upload-area:hover {
  border-color: #3498db;
  background: rgba(52, 152, 219, 0.05);
}

.file-upload-area.dragover {
  border-color: #2ecc71;
  background: rgba(46, 204, 113, 0.1);
}

.upload-placeholder i {
  font-size: 48px;
  color: #bdc3c7;
  margin-bottom: 15px;
  display: block;
}

.upload-placeholder p {
  font-size: 16px;
  color: #7f8c8d;
  margin-bottom: 10px;
}

.upload-placeholder small {
  color: #95a5a6;
  font-size: 14px;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 15px;
  background: rgba(52, 152, 219, 0.1);
  border-radius: 8px;
  margin: 10px 0;
}

.file-info i {
  color: #3498db;
  font-size: 20px;
}

.file-info span {
  font-weight: 500;
  color: #2c3e50;
}

.clear-btn {
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s;
}

.clear-btn:hover {
  background: #c0392b;
}

.uploaded-image {
  position: relative;
  display: inline-block;
}

.preview-image {
  max-width: 300px;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.uploaded-image .clear-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  background: #e74c3c;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.upload-actions {
  margin-top: 15px;
  text-align: center;
}

.upload-btn {
  background: linear-gradient(135deg, #3498db, #2980b9);
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.upload-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #2980b9, #21618c);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

.upload-btn:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.image-preview {
  margin-top: 15px;
  text-align: center;
}

.image-preview .preview-image {
  max-width: 300px;
  max-height: 200px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.image-preview .preview-image-small {
  max-width: 200px;
  max-height: 150px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 复选框样式 */
.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 0;
}

.checkbox-wrapper input[type="checkbox"] {
  width: 20px;
  height: 20px;
  cursor: pointer;
  margin: 0;
}

.checkbox-label {
  cursor: pointer;
  font-weight: 500;
  color: #2c3e50;
  margin: 0;
  user-select: none;
}

/* 输出格式类型选择样式 */
.output-type-options {
  display: flex;
  gap: 20px;
  margin-bottom: 12px;
  padding: 10px 0;
}

.type-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.type-option input[type="radio"] {
  margin: 0;
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.type-option label {
  margin: 0;
  cursor: pointer;
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
  user-select: none;
}

.output-section {
  margin-top: 8px;
}

.output-section textarea {
  width: 100%;
  padding: 12px 15px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 0.95em;
  transition: all 0.3s ease;
  background: white;
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.output-section textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 输出格式图片上传区域样式 */
.output-file-upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
}

.output-file-upload-area:hover {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

.upload-placeholder-small {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.upload-placeholder-small i {
  font-size: 32px;
  color: #bdc3c7;
}

.upload-placeholder-small p {
  font-size: 14px;
  color: #7f8c8d;
  margin: 0;
}

.upload-placeholder-small small {
  color: #95a5a6;
  font-size: 12px;
}

.file-info-small {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  padding: 12px;
  background: rgba(102, 126, 234, 0.1);
  border-radius: 6px;
}

.file-info-small i {
  color: #667eea;
  font-size: 18px;
}

.file-info-small span {
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
}

.clear-btn-small {
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 50%;
  width: 22px;
  height: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 11px;
  transition: background-color 0.3s;
  padding: 0;
}

.clear-btn-small:hover {
  background: #c0392b;
}

/* 测试用例样式 */
.test-cases-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.test-cases-header label {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.add-test-case-btn {
  padding: 8px 16px;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  box-shadow: 0 2px 8px rgba(76, 175, 80, 0.3);
}

.add-test-case-btn:hover {
  background: linear-gradient(135deg, #388e3c, #2e7d32);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.4);
}

.test-cases-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.no-test-cases {
  text-align: center;
  padding: 40px 20px;
  color: #7f8c8d;
  background: #f8f9fa;
  border-radius: 12px;
  border: 2px dashed #dee2e6;
}

.no-test-cases i {
  font-size: 32px;
  margin-bottom: 10px;
  color: #bdc3c7;
}

.no-test-cases p {
  margin: 0;
  font-size: 14px;
}

.test-case-item {
  background: white;
  border: 2px solid #e9ecef;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.test-case-item:hover {
  border-color: #667eea;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.1);
}

.test-case-header {
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.test-case-number {
  font-size: 16px;
  font-weight: 600;
}

.remove-test-case-btn {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}

.remove-test-case-btn:hover {
  background: rgba(231, 76, 60, 0.8);
  border-color: rgba(231, 76, 60, 0.8);
}

.test-case-content {
  padding: 20px;
}

.format-section {
  margin-bottom: 20px;
}

.format-section > label {
  display: block;
  font-size: 14px;
  font-weight: 600;
  color: #495057;
  margin-bottom: 10px;
}

.test-case-format {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e1e8ed;
  border-radius: 8px;
  font-size: 13px;
  transition: all 0.3s ease;
  background: #fff9e6;
  resize: vertical;
  min-height: 60px;
}

.test-case-format:focus {
  outline: none;
  border-color: #ffc107;
  box-shadow: 0 0 0 3px rgba(255, 193, 7, 0.1);
  background: white;
}

/* 测试用例文件上传区域 */
.test-case-file-upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
}

.test-case-file-upload-area:hover {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

.uploading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  color: #667eea;
}

.uploading-state i {
  font-size: 24px;
}

.uploading-state p {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.upload-success-hint {
  margin-top: 10px;
  padding: 8px 12px;
  background: #e8f5e9;
  color: #388e3c;
  border-radius: 6px;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.upload-success-hint i {
  color: #4CAF50;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .test-case-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .remove-test-case-btn {
    align-self: flex-end;
  }
}
</style> 